package com.sltx.service.impl;


import com.lowagie.text.Font;
import com.lowagie.text.Image;
import com.lowagie.text.*;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.rtf.RtfWriter2;
import com.sltx.dao.aaa.SubjectRepostMapper;
import com.sltx.util.PageData;
import com.sltx.util.TypeChange;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sun.misc.BASE64Decoder;

import java.awt.*;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SubjectReportServiceImpl  {

    @Autowired
    private SubjectRepostMapper mapper;


    /**
     * 获取对应年份所有行业相加总额
     * @param pd
     * @return
     */
    public Map getHylbskje(PageData pd){
        Map map = new HashMap();
        Map hylbskje = mapper.getHylbskje(pd);
        if (hylbskje ==null){
            hylbskje = new HashMap();
            hylbskje.put("tax_cash",0);
            hylbskje.put("city",0);
            hylbskje.put("cent",0);
            hylbskje.put("county",0);
        }
        Double tax_cash1 = (Double) hylbskje.get("tax_cash");
        Double city1 = (Double) hylbskje.get("city");
        Double cent1 = (Double) hylbskje.get("cent");
        Double county1 = (Double) hylbskje.get("county");
        String tax_cash = TypeChange.formatFloatNumber(tax_cash1);
        String cent = TypeChange.formatFloatNumber(cent1);
        String city = TypeChange.formatFloatNumber(city1);
        String county = TypeChange.formatFloatNumber(county1);
        hylbskje.put("tax_cash",tax_cash);
        hylbskje.put("cent",cent);
        hylbskje.put("city",city);
        hylbskje.put("county",county);

        hylbskje.put("industry_one_name","全部行业");
        map.put("qbhy",hylbskje);
        return hylbskje;
    }


    public List<Map> getAllByTax(PageData pd){
        List<Map> result = new ArrayList<>();
        List<Map> allByTax = mapper.getAllByTax(pd);
        Map e = null;
        for (int i=0; i<allByTax.size(); i++){
            Map map = allByTax.get(i);
            e = new HashMap();
            Object industry_one_name = map.get("industry_one_name");
            Object year = map.get("year");
            Double city1 = (Double) map.get("city");
            Double cent1 = (Double) map.get("cent");
            Double county1 = (Double) map.get("county");
            String cent = TypeChange.formatFloatNumber(cent1);
            String city = TypeChange.formatFloatNumber(city1);
            String county = TypeChange.formatFloatNumber(county1);
            e.put("industry_one_name",industry_one_name);
            e.put("year",year);
            e.put("cent",cent);
            e.put("city",city);
            e.put("county",county);
            result.add(e);

        }
        return result;
    }

    public List<Map> getZcdx(PageData pd){
        List<Map> result = new ArrayList<>();

        Map rcyj = mapper.getRcyj(pd);
        getNum(result, rcyj);

        Map xtznry = mapper.getXtznry(pd);
        getNum(result, xtznry);
        Map zdqy = mapper.getZdqy(pd);
        getNum(result, zdqy);
        Map gzjzz = mapper.getGzjzz(pd);
        getNum(result, gzjzz);
        Map gzf = mapper.getGzf(pd);
        getNum(result, gzf);
        Map hkzb = mapper.getHkzb(pd);
        getNum(result, hkzb);
        Map fjjyjs = mapper.getFjjyjs(pd);
        getNum(result, fjjyjs);
        Map lxsyj = mapper.getLxsyj(pd);
        getNum(result, lxsyj);


        return result;
    }

    // 获取政策兑现数量
    public void getNum(List<Map> result, Map rcyj) {
        if (rcyj != null) {
            Map rcyj1 = new HashMap();
            String num = rcyj.get("num").toString();
            rcyj1.put("num", num);
            result.add(rcyj1);
        } else {
            Map rcyj1 = new HashMap();
            rcyj1.put("num", 0);
            result.add(rcyj1);
        }
    }

    public Map getzc(PageData pd){
        String year = pd.get("year").toString();
        Map map = new HashMap();
        Map fjjyjs = mapper.getFjjyjs(pd);
        if (fjjyjs != null){
            String num = fjjyjs.get("num").toString();
            map.put("fjjyjs", num);
        }
        Map gzf = mapper.getGzf(pd);
        if (gzf != null){
            String num = gzf.get("num").toString();
            map.put("gzf", num);
        }
        Map gzjzz = mapper.getGzjzz(pd);
        if (gzjzz != null){
            String num = gzjzz.get("num").toString();
            map.put("gzjzz",num);
        }
        Map hkzb = mapper.getHkzb(pd);
        if (hkzb != null){
            String num = hkzb.get("num").toString();
            map.put("hkzb", num);
        }
        Map lxsyj = mapper.getLxsyj(pd);
        if (lxsyj != null){
            String num = lxsyj.get("num").toString();
            map.put("lxsyj",num);
        }
        Map rcyj = mapper.getRcyj(pd);
        if (rcyj != null){
            String num = rcyj.get("num").toString();
            map.put("rcyj", num);
        }
        Map xtznry = mapper.getXtznry(pd);
        if (xtznry != null){
            String num = xtznry.get("num").toString();
            map.put("xtznry", num);
        }
        Map zdqy = mapper.getZdqy(pd);
        if (zdqy != null){
            String num = zdqy.get("num").toString();
            map.put("zdqy", num);
        }
        map.put("year", year);
        return map;
    }

    /**
     * 获取企业变更报告全年工商和税务迁入迁出数据
     * @param pd
     * @return
     */
    public Map getQybg(PageData pd){
        String year = pd.get("year").toString();
        // 截取后两位字符
        String stryear = year.substring(year.length() -2,year.length());
        pd.put("stryear",stryear);

        Map yearQybg = mapper.getYearQybg(pd);

        return yearQybg;
    }

    public List<Map> getSwqr(PageData pd){
        String year = pd.get("year").toString();
        // 截取后两位字符
        String stryear = year.substring(year.length() -2,year.length());
        pd.put("stryear",stryear);

        List<Map> hylbSwqr = mapper.getHylbSwqr(pd);

        return hylbSwqr;
    }

    public List<Map> getSwqc(PageData pd){
        String year = pd.get("year").toString();
        // 截取后两位字符
        String stryear = year.substring(year.length() -2,year.length());
        pd.put("stryear",stryear);

        List<Map> hylbSwqc = mapper.getHylbSwqc(pd);
        return hylbSwqc;

    }


    public List<Map> getSw(PageData pd){
        String year = pd.get("year").toString();
        // 截取后两位字符
        String stryear = year.substring(year.length() -2,year.length());
        pd.put("stryear",stryear);
        List<Map> xx = new ArrayList<>();
        List<Map> hylbSwqr = mapper.getHylbSwqr(pd);
        List<Map> hylbSwqc = mapper.getHylbSwqc(pd);
        for (int i=0; i<hylbSwqr.size(); i++){
            Map map = hylbSwqr.get(i);
            String num = map.get("num").toString();
            String[] split = map.get("industry_cls").toString().split(" ");
            for (int j=0; j<hylbSwqc.size(); j++){
                Map map1 = hylbSwqc.get(j);
                String num1 = map1.get("num").toString();
                String[] split1 = map1.get("industry_cls").toString().split(" ");
                if (split[split.length-1].equals(split1[split1.length-1])){
                    Map temp = new HashMap();
                    temp.put("industry_cls",split[split.length-1]);
                    temp.put("swqr", num);
                    temp.put("swqc", num1);
                    xx.add(temp);
                }
            }
        }

        return xx;
    }



    public List<Map> getMonthgsqr(PageData pd){
        List<Map> gsqr = mapper.getMonthgsqr(pd);
        return  gsqr;
    }

    public List<Map> getMonthgsqc(PageData pd){
        List<Map> gsqc = mapper.getMonthgsqc(pd);
        return gsqc;
    }

    public List<Map> getMonthswqr(PageData pd){
        List<Map> swqr = mapper.getMonthswqr(pd);
        return swqr;
    }

    public List<Map> getMonthswqc(PageData pd){
        List<Map> swqc = mapper.getMonthswqc(pd);
        return swqc;
    }

    public String createDocContext(String fileName, String picBase64Info, PageData pd) {
        String docPath = "D:/aaa/";
        File file = new File(docPath + fileName);
        try {
            if (!file.exists()) {
                file.createNewFile();
            }
            // 创建文档，设置纸张大小
            Document document = new Document(PageSize.A4);
            // 建立一个书写器(Writer)与document对象关联，通过书写器(Writer)可以将文档写入到磁盘中
            RtfWriter2.getInstance(document, new FileOutputStream(file));
    //            RtfWriter2.getInstance(document, new FileOutputStream("D:/aaa"));
            document.open();
            // 设置中文字体
//            BaseFont bfChinese = BaseFont.createFont("C:/Windows/Fonts/simhei.ttf",
//                    BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            BaseFont bfChinese = BaseFont.createFont(BaseFont.COURIER, BaseFont.CP1257, BaseFont.EMBEDDED);
            //设置文字大小、字体、颜色
            Font fontChinese = new Font(bfChinese, 12, Font.NORMAL, Color.black);
            // 报告类型
            String type = pd.get("type").toString();
            // 年份
            String year = pd.get("year").toString();
            Font titleFont = new Font(bfChinese, 16, Font.BOLD);
            if ("纳税变动报告".equals(type)){//纳税变动报告
                String s = "北京市石景山区" + year + "年" + type;
                addParagraph(document, 1, titleFont, s,5,20);
                Map hylbskje = new HashMap();
                addNsbdContext(document, getHylbskje(pd));
                // 获取获取所有行业、所选年份 中央，市级，区级 对应年份累计金额
                List<Map> allByTax = getAllByTax(pd);
                if (allByTax != null){
                    document.add(createNsTable(fontChinese, allByTax));
                }
            }
            if ("政策兑现报告".equals(type)){//政策兑现报告
                String s = "北京市石景山区" + year+ "年" + type;
                addParagraph(document, 1, titleFont, s,5,20);
                Map zcdx = getzc(pd);
                addZcdxContext(document, zcdx);

                BASE64Decoder decoder =  new BASE64Decoder();

                byte[] imgByte = decoder.decodeBuffer(picBase64Info);
                // 对异常数据进行处理
                for (int i = 0; i < imgByte.length; i++) {
                    if (imgByte[i] < 0) {
                        imgByte[i] += 256;
                    }
                }
                String filen = "政策兑现柱状图" + ".png";
                //保存图片  写入本地磁盘中
                String name = docPath+filen;
                OutputStream out = new FileOutputStream(name);
                out.write(imgByte );
                out.flush();
                out.close();
                document.add(createImage(name));
            }
            if ("企业变更报告".equals(type)){//企业变更报告
                String s = "北京市石景山区" + year+ "年" + type;
                addParagraph(document, 1, titleFont, s,5,20);
                Map qybg = getQybg(pd);
                addQybgContext(document,qybg, year);
                List<Map> sw = getSw(pd);
                if (sw != null){
                    document.add( createQybgTable(fontChinese, sw));
                }

            }
            document.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return docPath + fileName;
    }

    // 添加标题
    private void addParagraph(Document document,int mode,Font titleFont,String context,int sapceSize,int indentSize) throws DocumentException {
        Paragraph summaryPara = new Paragraph(context);

        if(mode == 0){
            summaryPara.setAlignment(Element.ALIGN_LEFT);
        }else{
            summaryPara.setAlignment(Element.ALIGN_CENTER);
            summaryPara.setFont(titleFont);
        }
        //离上一段落（标题）空的行数
        if(sapceSize != 0){
            summaryPara.setSpacingBefore(sapceSize);
        }
        //设置第一行空的列数
        if(indentSize != 0){
            summaryPara.setFirstLineIndent(indentSize);
        }
        document.add(summaryPara);
        document.add(new Paragraph("\n"));
    }

    // 添加纳税变动字段描述
    private void addNsbdContext(Document document,Map e) throws Exception {
        String year = e.get("year").toString();
        String industry_one_name = String.valueOf(e.get("industry_one_name"));
        Object tax_cash = e.get("tax_cash");
        Object cent = e.get("cent");
        Object city = e.get("city");
        Object county = e.get("county");
        String conditionString = "截止"+year+"年，石景山区"+ industry_one_name+"行业税款总额"+tax_cash+"元，其中中央税款" +cent+"元、市级税款"+city+"元、区级税款"+county+"元";

//        BaseFont bfChinese = BaseFont.createFont("C:/Windows/Fonts/simhei.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
        BaseFont bfChinese = BaseFont.createFont(BaseFont.COURIER, BaseFont.CP1257, BaseFont.EMBEDDED);
        //设置文字大小、字体、颜色
        Font titleFont = new Font(bfChinese, 16, Font.BOLD);
        addParagraph(document, 0,titleFont, conditionString, 5, 20);


    }

    // 添加政策兑现字段描述
    private void addZcdxContext(Document document,Map e) throws Exception {

        String conditionString = "截止"+e.get("year")+"石景山区";

        if (e.get("rcyj") != null){
            conditionString += "人才引进落户共" + e.get("rcyj") +"人、";
        }

        if (e.get("xtznry") != null){
            conditionString += "协调子女入园入学共" + e.get("xtznry")+"人、";
        }

        if (e.get("zdqy") != null) {
            conditionString +="重点企业员工子女入园入学共" + e.get("zdqy")+"人、";
        }

        if (e.get("gzjzz") != null){
            conditionString += "工作居住证共"+e.get("gzjzz")+"人、";
        }

        if (e.get("gzf") != null){
            conditionString += "公租房共"+e.get("gzf") +"人、";
        }

        if (e.get("hkzb") != null){
            conditionString += "户口指标分配"+e.get("hkzb") +"人、";
        }

        if (e.get("fjjyjs") != null){
            conditionString += "非京籍应届生落户共" + e.get("fjjyjs")+"人、";
        }

        if ( e.get("lxsyj")!= null){
            conditionString += "留学生引进落户共" + e.get("lxsyj") + "人、";
        }

//        BaseFont bfChinese = BaseFont.createFont("C:/Windows/Fonts/simhei.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
        BaseFont bfChinese = BaseFont.createFont(BaseFont.COURIER, BaseFont.CP1257, BaseFont.EMBEDDED);
        //设置文字大小、字体、颜色
        Font titleFont = new Font(bfChinese, 16, Font.BOLD);
        addParagraph(document, 0,titleFont, conditionString, 5, 20);

    }


    // 添加企业变更字段描述
    private void addQybgContext(Document document,Map e, String year) throws Exception {
        String swqc = e.get("swqc").toString();
        String swqr = e.get("swqr").toString();
        String gsqr = e.get("gsqr").toString();
        String gsqc = e.get("gsqc").toString();
        String zdx = e.get("zdx").toString();
        String conditionString = "截止"+year+"年,石景山区注吊销企业共"+zdx+"家；迁入企业中，工商迁入企业共"+gsqr+"家、税务迁入企业共"+swqr+"家；迁出企业中，工商迁出企业共"+gsqc+"家、税务迁出企业共"+swqc+"家";
        BaseFont bfChinese = BaseFont.createFont(BaseFont.COURIER, BaseFont.CP1257, BaseFont.EMBEDDED);
        //设置文字大小、字体、颜色
        Font titleFont = new Font(bfChinese, 16, Font.BOLD);
        addParagraph(document, 0,titleFont, conditionString, 5, 20);

    }

    // 创建纳税变动报告表格
    private Table createNsTable(Font fontChinese,List<Map> dataList){
        //设置跨产业   Table表格
        Table aTable = null;
        try {
            // 创建表格为几列、每列的宽度
            aTable = new Table(4);
            int width[] = {20, 16, 16, 16};
            setTablePro(aTable, width);
            // 设置标题列
            Cell[] cellHeader = new Cell[4];
            cellHeader[0] = new Cell(new Phrase("行业类别",fontChinese));
            cellHeader[1] = new Cell(new Phrase("中央纳税金额",fontChinese));
            cellHeader[2] = new Cell(new Phrase("市级纳税金额",fontChinese));
            cellHeader[3] = new Cell(new Phrase("区级纳税金额",fontChinese));
            // 设置单元格式
            for (int i=0; i<cellHeader.length; i++){
                /** 居中显示 */
                cellHeader[i].setHorizontalAlignment(Element.ALIGN_CENTER);
                /** 纵向居中显示*/
                cellHeader[i].setVerticalAlignment(Element.ALIGN_MIDDLE);
                aTable.addCell(cellHeader[i]);
            }
            // 像表格填充数据
            for (int i=0; i<dataList.size(); i++){
                Map pd = dataList.get(i);
                Cell[] cell = new Cell[4];
                cell[0] = new Cell(new Phrase(pd.get("industry_one_name").toString(),fontChinese));
                cell[1] = new Cell(new Phrase(pd.get("cent").toString(),fontChinese));
                cell[2] = new Cell(new Phrase(pd.get("city").toString(),fontChinese));
                cell[3] = new Cell(new Phrase(pd.get("county").toString(),fontChinese));
                for (int j = 0; j < cell.length; j++) {
                    if(j == 2 || j == 4|| j == 3){
                        /** 居右显示  */
                        cell[j].setHorizontalAlignment(Element.ALIGN_RIGHT);
                        /** 纵向居中显示*/
                        cell[j].setVerticalAlignment(Element.ALIGN_MIDDLE);
                    }else{
                        /** 居中显示 */
                        cell[j].setHorizontalAlignment(Element.ALIGN_CENTER);
                        /** 纵向居中显示*/
                        cell[j].setVerticalAlignment(Element.ALIGN_MIDDLE);
                    }
                    aTable.addCell(cell[j]);
                }
            }

        } catch (BadElementException e) {
            e.printStackTrace();
        }
        return aTable;
    }

    // 创建企业变更表格
    private Table createQybgTable(Font fontChinese,List<Map> dataList){
        Table aTable = null;
        try {
            // 创建表格为几列、每列的宽度
            aTable = new Table(3);
            int width[] = {20, 16, 16 };
            setTablePro(aTable, width);
            // 设置标题列
            Cell[] cellHeader = new Cell[3];
            cellHeader[0] = new Cell(new Phrase("行业类别",fontChinese));
            cellHeader[1] = new Cell(new Phrase("税务迁入",fontChinese));
            cellHeader[2] = new Cell(new Phrase("税务迁出",fontChinese));
            // 设置单元格式
            for (int i=0; i<cellHeader.length; i++){
                /** 居中显示 */
                cellHeader[i].setHorizontalAlignment(Element.ALIGN_CENTER);
                /** 纵向居中显示*/
                cellHeader[i].setVerticalAlignment(Element.ALIGN_MIDDLE);
                aTable.addCell(cellHeader[i]);
            }
            for (int i=0; i<dataList.size(); i++) {
                Map pd = dataList.get(i);
                Cell[] cell = new Cell[3];
                cell[0] = new Cell(new Phrase(pd.get("industry_cls").toString(),fontChinese));
                cell[1] = new Cell(new Phrase(pd.get("swqr").toString(),fontChinese));
                cell[2] = new Cell(new Phrase(pd.get("swqc").toString(),fontChinese));
                for (int j = 0; j < cell.length; j++) {
                    if(j == 1 || j == 2){
                        /** 居右显示*/
                        cell[j].setHorizontalAlignment(Element.ALIGN_CENTER);
                        /** 纵向居中显示*/
                        cell[j].setVerticalAlignment(Element.ALIGN_MIDDLE);
                    }else{
                        /** 居中显示 */
                        cell[j].setHorizontalAlignment(Element.ALIGN_CENTER);
                        /** 纵向居中显示*/
                        cell[j].setVerticalAlignment(Element.ALIGN_MIDDLE);
                    }
                    aTable.addCell(cell[j]);
                }

            }

        }catch (BadElementException e){
            e.printStackTrace();
        }
        return  aTable;
    }

    /*
     * 设置表格属性
     */
    private void setTablePro(Table table,int width[]){
        try{
            table.setWidths(width);// 设置每列所占比例
            table.setWidth(100); // 占页面宽度 90%
            table.setAlignment(Element.ALIGN_CENTER);// 居中显示
            table.setAlignment(Element.ALIGN_MIDDLE);// 纵向居中显示
            table.setAutoFillEmptyCells(true); // 自动填满
            table.setBorderWidth(1); // 边框宽度
            table.setBorderColor(new Color(0, 0, 0)); // 边框颜色
            table.setPadding(2);// 衬距，看效果就知道什么意思了
            table.setBorder(2);// 边框
        }catch(Exception e){
            System.out.print(e.toString());
        }
    }
    public Image createImage( String name) throws IOException {

        Image img = null;
        try {
            img = Image.getInstance(name);
            img.setAbsolutePosition(0, 0);
            img.setAlignment(Image.LEFT);// 设置图片显示位置
            img.scaleAbsolute(523, 382);
        } catch (BadElementException e) {
            e.printStackTrace();
        }

        return img;

    }

}
